package main

import (
	"fmt"
	"unicode/utf8"
)

/**
字符和字符串处理
1.rune相当于go的char
(1) 使用range遍历pos, rune对
(2) 使用utf8.RuneCountInString获得字符数量
(3) 使用len获得字节长度
(4) 使用[]byte获得字节
2.其他字符串操作
(1) Fields, Split, Join
(2) Contains, Index
(3) ToLower,ToUpper
(4) Trim,TrimRight, TrimLeft

*/
func main() {
	s := "Yes我爱慕课网!" // UTF-8
	fmt.Println(s)
	for _, b := range []byte(s) {
		fmt.Printf("%X", b)
	}
	fmt.Println()

	for i, ch := range s { // ch is a rune
		fmt.Printf("(%d %X)", i, ch)
	}
	fmt.Println()

	fmt.Println("Rune count:", utf8.RuneCountInString(s))

	bytes := []byte(s)
	for len(bytes) > 0 {
		ch, size := utf8.DecodeRune(bytes)
		bytes = bytes[size:]
		fmt.Printf("%c ", ch)
	}
	fmt.Println()

	for i, ch := range []rune(s) {
		fmt.Printf("(%d %c)", i, ch)
	}
	fmt.Println()

	fmt.Println(lengthOfNonRepeatinqSubStr2("这里是慕课网"))
	fmt.Println(lengthOfNonRepeatinqSubStr2("一二三二一"))
	fmt.Println(lengthOfNonRepeatinqSubStr2("黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"))
}

// 例：寻找最长不含有重复字符的子串 国际版 可以使用中文
func lengthOfNonRepeatinqSubStr2(s string) int {
	lastOccurred := make(map[rune]int)
	start := 0
	maxLength := 0
	for i, ch := range []rune(s) {
		if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
			start = lastI + 1
		}
		if i-start+1 > maxLength {
			maxLength = i - start + 1
		}
		lastOccurred[ch] = i
	}

	return maxLength
}
